package cn.mengfly.fxtest.app.urltest;

import javafx.beans.property.*;
import javafx.concurrent.Service;
import javafx.concurrent.Task;

/**
 * @author Mengfly
 */
public class UrlTestViewModel {
    private final StringProperty statusCode = new SimpleStringProperty();
    private final StringProperty loadTime = new SimpleStringProperty();
    private final StringProperty url = new SimpleStringProperty();

    private final StringProperty errorMessage = new SimpleStringProperty();
    private final BooleanProperty wasError = new SimpleBooleanProperty(false);

    private final UrlTestModel urlTestModel = new UrlTestModel();

    private final Notifications notification = new Notifications();

    private final Service<Void> urlTestCommand = new Service<Void>() {
        @Override
        protected Task<Void> createTask() {
            return new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    updateProgress(0.1, 1);
                    updateMessage("Testing url" + url.get());
                    urlTestModel.testUrl(url.get());
                    return null;
                }

                @Override
                protected void failed() {
                    getException().printStackTrace();
                }
            };
        }
    };

    public UrlTestViewModel() {
        notification.subscribe(Notifications.EVENT_MODEL_UPDATE, this, this::update);
    }

    private void update(String event) {
        urlTestModel.getUrlTestObject().ifPresent(testObj -> {
            wasError.set(testObj.getWasError());

            if (!testObj.getWasError()) {
                statusCode.set("Status Code:" + testObj.getStatusCode());
                loadTime.set(testObj.getLoadTime() + " ms");
            } else {
                statusCode.set("");
                loadTime.set("");
            }
            errorMessage.set(testObj.getErrorMessage());

        });
    }

    public StringProperty statusCodeProperty() {
        return statusCode;
    }

    public StringProperty loadTimeProperty() {
        return loadTime;
    }

    public StringProperty urlProperty() {
        return url;
    }

    public ReadOnlyBooleanProperty urlTestTaskRunningProperty() {
        return urlTestCommand.runningProperty();
    }

    public ReadOnlyDoubleProperty urlTestTaskProgressProperty() {
        return urlTestCommand.progressProperty();
    }

    public ReadOnlyStringProperty urlTestTaskMessageProperty() {
        return urlTestCommand.messageProperty();
    }

    public void test() {
        urlTestCommand.restart();
    }

    public StringProperty errorMessageProperty() {
        return errorMessage;

    }
}
